#!/usr/bin/env python
import json
import time
from time import sleep
import requests

name = 'openharmony'
project_path_list = []
projext_path_admin = []
token = '350c5ee32d7861f903590f676c4566a0'



def list_org_repo(token, name, type = 'all'):
    url = F'https://gitee.com/api/v5/orgs/{name}/repos'
    page_end = None
    page = 1
    per_page = 100
    params = {
        'access_token': token,
        'per_page': per_page,
        'type': type,
    }

    cnt = 0
    while page_end == None or page <= page_end:
        params['page'] = page
        rsp = requests.get(url, params=params)
        content = json.loads(rsp.content)
        page_end = int(rsp.headers['total_page'])
        total = int(rsp.headers['total_count'])
        for item in content:
            cnt += 1
            yield item, cnt, total
        page += 1

def fork(token, project_path):

    data = {
        'access_token': token,
    }
    url = F" https://gitee.com/api/v5/repos/{project_path}/forks"
    rsp = requests.post(url, data)
    return [False,True][rsp.status_code == 201]
    # if rsp.status_code == 201:
    #     print(F'{project_path}仓库创建完毕')
    #     return Ture
    # else:
    #     print(F'{project_path}仓库创建失败')
    #     # time.sleep(1)
    #     new_repo_fail.append(project_path)
    # return new_repo_fail

def dellet(token, repo_name):
    new_repo_fail = []
    url = F" https://gitee.com/api/v5/repos/sig-ci-test/{repo_name}?access_token={token}"
    rsp = requests.delete(url)
    return [False,True][rsp.status_code == 204]
    # if rsp.status_code == 204:
    #     print(F'{project_path}仓库删除完毕')
    #     # time.sleep(5)
    # else:
    #     print(F'{project_path}仓库删除失败')
    #     new_repo_fail.append(project_path)
    #     # time.sleep(5)
    # return new_repo_fail

# 获取组织的所有仓库
list_org_repo_name = list_org_repo(token, name, type = 'all')
repo_count = 0
new_repo_fail = []
repo_dellet_fail = []
for repo, current, total in list_org_repo_name:
    repo_count += 1
    project_path = repo['full_name']
    print(project_path)
    repo_name = project_path[project_path.index('/')+1:]
    project_path_list.append(repo_name)
    # list_del = dellet(token, project_path[project_path.index('/')+1:])
    if not dellet(token, repo_name): 
        repo_dellet_fail.append(repo_name)
    if not fork(token, project_path): 
        new_repo_fail.append(repo_name)
print(F'fork失败{new_repo_fail}')
print(F'删除失败{repo_dellet_fail}')